<template>
    <div>
        <div class="userManager">
            <div class="queryForm">
                <query-form
                    :form="searchLabel"
                    v-model="targetForm"
                    @searchHandler="search"
                    @cancelHandler="resetSearch"
                ></query-form>
            </div>
            <div class="baseTable">
                <!-- <base-table></base-table> -->
                <div class="action">
                    <el-button type="primary" @click="deptAdd" v-has="'dept-create'">
                        新增
                    </el-button>
                </div>
                <el-table
                    ref="listRef"
                    :data="deptList"
                    style="width: 100%"
                    row-key="_id"
                    :tree-props="{ children: 'children' }"
                >
                    <el-table-column
                        v-for="ele in columns"
                        :key="ele.prop"
                        :prop="ele.prop"
                        :label="ele.label"
                        :formatter="ele.formatter"
                        :width="ele.width"
                    />
                    <el-table-column label="操作" min-width="120">
                        <template #default="scope">
                            <el-button
                                type="primary"
                                @click="deptEdit(scope.row)"
                                :icon="Edit"
                                v-show="scope.row.parentId[0] != null"
                                v-has="'dept-edit'"
                            />
                            <el-button
                                type="danger"
                                @click="deptDelete(scope.row)"
                                :icon="Delete"
                                v-show="scope.row.parentId[0] != null"
                                v-has="'dept-delete'"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <el-dialog v-model="showDialog" @close="close">
                <el-form :model="deptForm" ref="dialogForm" :rules="rules">
                    <el-form-item label="上级部门" prop="parentId">
                        <el-cascader
                            v-model="deptForm.parentId"
                            :options="deptList"
                            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
                            clearable
                            placeholder="请选择上级部门"
                        />
                    </el-form-item>
                    <el-form-item label="部门名称" prop="deptName">
                        <el-input v-model="deptForm.deptName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="负责人" prop="userName">
                        <el-select v-model="deptForm.userName" placeholder="请选择负责人">
                            <el-option
                                v-for="item in userList"
                                :key="item._id"
                                :label="item.userName"
                                :value="item.userName"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责人邮箱" prop="userEmail">
                        <el-input v-model="email" autocomplete="off" disabled />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="submit(dialogForm)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { computed, nextTick, reactive, ref, toRaw } from 'vue';
import api from '../api';
import utils from '../utils';
/*节点、表单、请求体*/
const deptList = ref([]);
const userList = ref([]);
const dialogForm = ref(null);
const targetRef = ref(null);
const columns = reactive([
    {
        label: '部门名字',
        prop: 'deptName',
        width: 150,
    },
    {
        label: '负责人',
        prop: 'userName',
    },
    {
        label: '更新时间',
        prop: 'updateTime',
        formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
        },
        width: 210,
    },
    {
        label: '创建时间',
        prop: 'createTime',
        formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
        },
        width: 210,
    },
]);
const searchLabel = [
    {
        type: 'input',
        label: '部门名字',
        prop: 'targetName',
        placeholder: '请输入部门名字',
    },
];
const rules = reactive({
    parentId: [
        {
            required: true,
            message: '请选择上级部门',
            trigger: 'blur',
        },
    ],
    deptName: [
        {
            required: true,
            message: '请输入部门名称',
            trigger: 'blur',
        },
        {
            min: 2,
            max: 10,
            message: '长度在2-8个字符',
            trigger: 'blur',
        },
    ],
    userName: [
        {
            required: true,
            message: '请选择负责人',
            trigger: 'blur',
        },
    ],
});
const deptForm = reactive({});
const targetForm = reactive({});

/*普通变量*/
const showDialog = ref(false);
let email = computed(() => {
    if (deptForm.userName) {
        return userList.value.filter(ele => ele.userName == deptForm.userName)[0].userEmail;
    } else {
        return '暂无负责人';
    }
});
let action = ref('add');
/*用于请求的函数*/
const getDeptList = async params => {
    deptList.value = await api.getDeptList(params);
};
const operateDept = async data => {
    let res = await api.deptOperate(data);
};
const getAllUser = async () => {
    userList.value = await api.getAllUserList();
};
/*点击事件函数*/
const deptAdd = () => {
    action.value = 'create';
    showDialog.value = !showDialog.value;
};
const submit = row => {
    row.validate(async vaild => {
        if (vaild) {
            try {
                let form = toRaw(deptForm);
                let userMsg = userList.value.filter(ele => ele.userName == deptForm.userName)[0];
                let data = { ...form, ...userMsg };
                delete data['_id'];
                data['action'] = action.value;
                console.log(data);
                await operateDept(data);
                getDeptList();
                showDialog.value = !showDialog.value;
                resetForm();
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                });
            } catch (error) {
                ElMessage.error('提交失败');
            }
        }
    });
};
const cancel = () => {
    showDialog.value = !showDialog.value;
    resetForm();
};
const close = () => {
    resetForm();
};
const deptEdit = row => {
    action.value = 'edit';
    showDialog.value = !showDialog.value;
    nextTick(() => {
        Object.assign(deptForm, row);
    });
};
const deptDelete = row => {
    action.value = 'delete';
    let data = {
        _id: row._id,
    };
    data['action'] = action.value;
    operateDept(data);
    getDeptList();
};
const search = () => {
    let target = {
        deptName: targetForm.targetName,
    };
    getDeptList(target);
};
const resetSearch = () => {
    getDeptList();
};
/*交互事件函数*/
const resetForm = () => {
    dialogForm.value.resetFields();
};
/*调用*/
getDeptList();
getAllUser();
</script>

<style lang="scss" scoped>
.userManager {
    .queryForm {
        width: 100%;
        height: 65px;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        display: flex;
        align-items: center;
        padding-top: 20px;
        padding-left: 40px;
    }
    .baseTable {
        margin-top: 20px;
        background-color: #fff;
        border-radius: 8px;
        overflow: hidden;
        .action {
            width: 100%;
            height: 55px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #f1f1f1;
            button {
                margin-left: 20px;
                font-weight: bold;
            }
        }
    }
}
</style>
